/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

/*
 * JSQL Memory To Query/Operate Javascript Object
 * Can use basic sql language
 * select , insert , update , delete , create table , drop table
 * 
 */

YESBRAIN.namespace("JSQL.Memory");

YESBRAIN.JSQL.Memory = {
		
		executeSQL : function(sql) {
			var re = new RegExp(/\s*(select|insert|update|delete|create\s+table|drop\s+table)/ig);
			var res;
			res = re.exec(sql);
			if(res) {
				var cmd = res[1];
				cmd = cmd.toLowerCase().replace(" ","");
				if(cmd=="select") {
					return YESBRAIN.JSQL.Memory.QUERY.query(sql);
				} else if(cmd=="insert") {
					return YESBRAIN.JSQL.Memory.INSERT.executeInsert(sql);
				} else if(cmd=="update") {
					return YESBRAIN.JSQL.Memory.UPDATE.executeUpdate(sql);
				} 
				else if(cmd=="delete") {
					return YESBRAIN.JSQL.Memory.DELETE.executeDelete(sql);
				}
				else if(cmd=="createtable") {
					return YESBRAIN.JSQL.Memory.CREATETABLE.executeCreateTable(sql);
				}
				else if(cmd=="droptable") {
					return YESBRAIN.JSQL.Memory.DROPTABLE.executeDropTable(sql);
				}
				else
				{
					alert("SQL command error!");
					return null;
				};
			} else {
				alert("command not supported yet!");
				return null;
			};
		},
		
		querySQL : function(sql){
			return this.executeSQL(sql);
		}
		
	};

/*
 * Select SQL Language
 * Can use basic select language
 * select , from , where , like , group by , order by
 * select count(*) , max(*) , min(*), sum(*), avg(*)
 * 
 */

YESBRAIN.JSQL.Memory.QUERY = {
	parseTopCount : function(sql) {
		var re = new RegExp(/\s+top\s+/ig);
		var ree;
		var res;
		res = re.exec(sql);
		if(res){
			ree = new RegExp(/top\s+(\d+)\s+/ig);
			res = ree.exec(sql);
		};
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseCols : function(sql) {
		var re = new RegExp(/\s+top\s+/ig);
		var ree;
		var res;
		res = re.exec(sql);
		if(res){
			ree = new RegExp(/top\s+\d+\s+(.+)\s+from/ig);
		}
		else {
			ree = new RegExp(/select\s+(.+)\s+from/ig);
	    };
		//var sql = "select * from";
		res = ree.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseTables : function(sql){
		//var sql = "select * from test";
		var re = new RegExp(/\s+(where|group|order)\s+/ig);
		var ree;
		var res;
		res = re.exec(sql);
		if(res) {
			var cmd = res[1].toLowerCase();
			ree = new RegExp("from\\s+(.+)\\s+" + cmd);
			ree.ignoreCase = true;
			ree.global = true;
		} else {
			ree = new RegExp(/from\s+(.+)\s*$/ig);
		};
		res = ree.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseConditions : function(sql) {
		//var sql = "select * from test where a=a group by order by ";
		var res;
		var ree;
		var re = new RegExp(/\s+where\s+/ig);
		var re2 = new RegExp(/group\s+by/ig);
		var re3 = new RegExp(/order\s+by/ig);
		if(re.exec(sql)) {
			if(re2.exec(sql)) {
				var ree = new RegExp(/where(.+)group\s+by/ig);
			}
			else if(re3.exec(sql)) {
				var ree = new RegExp(/where(.+)order\s+by/ig);
				//res = re3.exec(sql);
			}
			else {
				ree = new RegExp(/where(.+)$/ig);
			};
		res = ree.exec(sql);
		} else {
			return "true";
		};
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseGroupCols : function(sql){
		var re = new RegExp(/group\s+by/ig);
		var re2 = new RegExp(/order\s+by/ig);
		var ree;
		var res;
		if (re.exec(sql)) {
			if (re2.exec(sql)) {
				ree = new RegExp(/group\s+by\s+(.+)order\s+by/ig);
			}
			else {
				ree = new RegExp(/group\s+by\s+(.+)$/ig);
			};
			res = ree.exec(sql);
			return res[1];
		}
		else {
			return null;
		};
	},
	
	parseOrderCols : function(sql) {
		//var sql = "select * from test order by id desc ";
		var re = new RegExp(/order\s+by/ig);
		var ree;
		var res;
		if(re.exec(sql)) {
			ree = new RegExp(/order\s+by(.+)$/ig);
			res = ree.exec(sql);
			return res[1];
		} else {
			//res = null;
			return null;
		};
	},
	
	splitCols : function(cols) {
		var colObjs = [];
		if(cols=="*") {
			return "*";
		};
		var colsArr;
		var res;
		colsArr = cols.split(',');
		for(var i=0;i<colsArr.length;i++) {
			var colObj = {};
			var re = new RegExp(/\s*(.+)\s+as\s+(.+)\s*/ig);
			res = re.exec(colsArr[i]);
			if(res) {
				colObj["col"] = res[1];
				colObj["alias"] = res[2];
			} else {
				colObj["col"] = colsArr[i];
				//colObj["alias"] = colsArr[i];
			};
			var re2 = new RegExp(/(count|sum|avg|max|min)\((.+)\)/ig);
			res = re2.exec(colObj["col"]);
			if(res) {
				colObj["sqlfunc"] = res[1].toLowerCase();
				colObj["col"] = res[2];
				//colObj["alias"] = "";
			};
			colObjs.push(colObj);
		};
		return colObjs;
	},
	
	splitTables : function(tables) {
		var tablesArr;
		var tableObj = {};
		var tableObjs = [];
		var res;
		tablesArr = tables.split(',');
		for(var i=0;i<tablesArr.length;i++) {
			var re = new RegExp(/\s*(.+)\s+as\s+(.+)\s*/ig);
			res = re.exec(tablesArr[i]);
			if(res) {
				tableObj["table"] = res[1];
				tableObj["alias"] = res[2];
			} else {
				tableObj["table"] = tablesArr[i];
				//tableObj["alias"] = "";
			}
			tableObjs.push(tableObj);
		};
		return tableObjs;
	},
	
	splitOrders : function(orders) {
		var ordersArr;
		var orderObjects = [];
		var res;
		ordersArr = orders.split(',');
		for(var i=0;i<ordersArr.length;i++) {
			var orderObject = {};
			var re = new RegExp(/\s*(.+)\s+(.+)\s*/ig);
			res = re.exec(ordersArr[i]);
			orderObject["sortby"] = res[1];
			orderObject["order"] = res[2];
			orderObjects.push(orderObject);
		}
		return orderObjects;
	},
	
	equallike : function(Str, likeStr) {

		likeStr = likeStr.replace(/\%/ig,".+");
		likeStr = likeStr.replace(/\?/ig,".?");
		likeStr = likeStr.replace(/\*/ig,".?");
		var re2 = new RegExp(likeStr);
		re2.ignoreCase = true;
		re2.global = true;
		var ok = re2.exec(Str);
		return ok;
	},
	
	splitConditions : function(conditions) {
		
		/*
		 * 
		   myobj = {
			a: 11,
			b: 'c',
			ok: true,
			ttt: '123'
		};
		
		
		
		 * OLD FUNCTION
		var re = /and/ig;
		var re2 = /or/ig;
		var re3 = /[^<=>]\=/ig;
		conditions = conditions.replace(re,"&&");
		conditions = conditions.replace(re2,"||");
		conditions = conditions.replace(re3,"==");
		alert(conditions);
		*/

		var conditionsArr;
		var re = new RegExp(/(and|or)/ig);
		var re2 = new RegExp(/([^<=>])\=/ig);
		var re3 = new RegExp(/\s+(.+)\s+like\s+(.+)/ig);
		var res = '';
		conditionsArr = conditions.split(re);
		for(var i=0;i<conditionsArr.length;i++) {
			curCondition = conditionsArr[i];
			curCondition = curCondition.replace(re2,"$1==");
			curCondition = curCondition.replace(re3," this.equallike($1,$2)");
			conditionsArr[i] = curCondition;
		};
		for (var i = 0; i < conditionsArr.length; i++) {
			var tmpStr = conditionsArr[i];
			if (tmpStr.toLowerCase() == 'and') {
				tmpStr = '&&';
			}
			else if (tmpStr.toLowerCase() == 'or') {
				tmpStr = '||';
			};
			res = res + tmpStr;
		};
		return res;
		/*
		alert(res);
		with(myobj) {
			equalreturn = eval(res);
			//window.document.getElementById('testout').innerHTML=conditions;
			//equalreturn = eval("((a>=11&&b=='c')||ok==turue&&equallike(ttt,'abc'))");
			alert(equalreturn);
		};
		*/
	},

	
	GroupByCol : function(Records, col) {
		
		/*
		 * There are Two Type : Records / Groups
		 * Records = {
		 * 				type: 'records',
		 * 				col: '',
		 * 				records: []
		 * 			  }
		 * 
		 * Groups = {
		 * 				type: 'groups',
		 * 				col: 'colname',
		 * 				groups: {}
		 * 			}
		 */
		
		var Groups = {
						type: 'groups',
						col: col,
						groups: {}
		};
		
		if (Records.type == 'records') {
			for (var i = 0; i < Records.records.length; i++) {
				with (Records.records[i]) {
					var colby = eval(col);
					if (!YESBRAIN.lang.isObject(Groups.groups[colby])) {
						var grouprecords = {
							type: 'records',
							col: '',
							records: []
						};
						Groups.groups[colby] = grouprecords;
					};
					Groups.groups[colby].records.push(Records.records[i]);
				}
				
			}
			return Groups;
		}
		else 
			if (Records.type == 'groups') {
				for(var group in Records.groups) {
					Records.groups[group] = this.GroupByCol(Records.groups[group],col);
				};
				return Records;
			};
		
	},
	
	getGroupedRecords : function(Records) {
		if (Records.type == "records") {
			if (Records.records.length<1) {return null;};
			var _count_ = Records.records.length;
			for(var p in Records.records[0]) {
				if (YESBRAIN.lang.isNumber(Records.records[0][p])) {
					var _number_sum_ = 0;
					var _number_max_ = Records.records[0][p];
					var _number_min_ = Records.records[0][p];
					var _number_avg_ = 0;
					for (var i = 0; i < Records.records.length; i++) {
						var record = Records.records[i];
						_number_sum_ = _number_sum_ + record[p];
						_number_max_ = Math.max(_number_max_, record[p]);
						_number_min_ = Math.min(_number_min_, record[p]);
					};
					_number_avg_ = _number_sum_ / _count_;
					
					Records.records[0]['_sum_'+p] = _number_sum_;
					Records.records[0]['_max_'+p] = _number_max_;
					Records.records[0]['_min_'+p] = _number_min_;
					Records.records[0]['_avg_'+p] = _number_avg_;
				};
			};
			Records.records[0]._count = _count_;
			
			Records.records.length = 1;
			return Records;
		}
		else if (Records.type == "groups") {
			var returnrecords = {
				//_count: 0,
				//_sum: 0,
				//_max: 0,
				//_min: 0,
				type: "records",
				col: "",
				records: []
			};
			for(var group in Records.groups) {
				var onegroup = Records.groups[group];
				var grouprecords = this.getGroupedRecords(onegroup);
				//._count = returnrecords._count + grouprecords._count;
				returnrecords.records = returnrecords.records.concat(grouprecords.records);
			}
			return returnrecords;
		}
	},
	
	sortRecords : function(Records,sortby,order) {
		function _number_asc_func(a,b) {
			return a[sortby]-b[sortby];
		};
		function _number_desc_func(a,b) {
			return b[sortby]-a[sortby];
		};
		
		function _string_asc_func(a,b) {
			return a[sortby].localeCompare(b[sortby]);
		};
		function _string_desc_func(a,b) {
			return b[sortby].localeCompare(a[sortby]);
		};
		
		
		if(Records.type == "records") {
			if(Records.records.length<1) {return null;};
			if (YESBRAIN.lang.isNumber(Records.records[0][sortby])) {
				if (order.toLowerCase() == "asc") {
					Records.records = Records.records.sort(_number_asc_func);
				}
				else 
					if (order.toLowerCase() == "desc") {
						Records.records = Records.records.sort(_number_desc_func);
					}
				return Records;
			} else if(YESBRAIN.lang.isString(Records.records[0][sortby])){
				if (order.toLowerCase() == "asc") {
					Records.records = Records.records.sort(_string_asc_func);
				}
				else 
					if (order.toLowerCase() == "desc") {
						Records.records = Records.records.sort(_string_desc_func);
					}
				return Records;
			}
		} else {
			return null;
		}
	},
	
	query : function(sql) {
		var tables = this.parseTables(sql);
		var tableobjs = this.splitTables(tables);
		var table = eval(tableobjs[0].table);
		if(table.length<1) {return null;};
		table = {
				type: "records",
				col: "",
				records: table
		};
		var topcount = this.parseTopCount(sql);
		if(!topcount) {
			topcount = eval(topcount);
		};
		var cols = this.parseCols(sql);
		if (cols != "*") {
			cols = this.splitCols(cols);
		};
		var conditions = this.parseConditions(sql);
		conditions = this.splitConditions(conditions);
		
		var returnobjs = {
							type: "records",
							col: "",
							records: []
		
		};
		if(table.records.length<1) {return null;};
		for(var i=0;i<table.records.length;i++) {
			with(table.records[i]) {
				var equalreturn = eval(conditions);
				if (equalreturn) {
					returnobjs.records.push(table.records[i]);
				}
			}
		};
		
		if(returnobjs.records.length<1) {return null;};
		
		var groups = this.parseGroupCols(sql);
		if(groups) {
			var groupobjs = this.splitCols(groups);
			for(var i=groupobjs.length-1;i>=0;i--) {
				returnobjs = this.GroupByCol(returnobjs,groupobjs[i]["col"]);
			};
			returnobjs = this.getGroupedRecords(returnobjs);
		} else {
			if (returnobjs.records.length<1) {return null;};
			var _count_ = returnobjs.records.length;
			for(var p  in returnobjs.records[0]) {
				if (YESBRAIN.lang.isNumber(returnobjs.records[0][p])) {
					var _number_sum_ = 0;
					var _number_max_ = returnobjs.records[0][p];
					var _number_min_ = returnobjs.records[0][p];
					var _number_avg_ = 0;
					for (var i = 0; i < returnobjs.records.length; i++) {
						var record = returnobjs.records[i];
						_number_sum_ = _number_sum_ + record[p];
						_number_max_ = Math.max(_number_max_, record[p]);
						_number_min_ = Math.min(_number_min_, record[p]);
					};
					_number_avg_ = _number_sum_ / _count_;
					
					returnobjs['_sum_'+p] = _number_sum_;
					returnobjs['_max_'+p] = _number_max_;
					returnobjs['_min_'+p] = _number_min_;
					returnobjs['_avg_'+p] = _number_avg_;
				};
			};
			returnobjs._count = _count_;
		};
		
		if(returnobjs.records.length<1) {return null;};
		
		var orders = this.parseOrderCols(sql);
		
		if(orders) {
			var orderobjs = this.splitOrders(orders);
			for(var i=orderobjs.length-1;i>=0;i--) {
				returnobjs = this.sortRecords(returnobjs,orderobjs[i]["sortby"],orderobjs[i]["order"]);
			};
		};
		
		if (cols != "*") {
			var returnrecords = returnobjs.records;
			returnobjs.records = [];
			for(var i=0;i<returnrecords.length;i++) {
				if(topcount&&(i>topcount-1)) {
					break;
				};
				var newobj = {};
				for(var j=0;j<cols.length;j++) {
					var alias;
					if (cols[j].sqlfunc=="count") {
						alias = cols[j].alias ? cols[j].alias : "field" + (j + 1) ;
						var _count = returnobjs._count ? returnobjs._count : returnrecords[i]["_count"];
						newobj[alias] = _count;
					}
					else if ((cols[j].sqlfunc!=null)&&(cols[j].sqlfunc!="")) { 
						alias = cols[j].alias ? cols[j].alias : "field" + (j + 1) ;
						var _property = "_"+cols[j].sqlfunc+"_" + cols[j].col;
						var _number = returnobjs[_property] ? returnobjs[_property] : returnrecords[i][_property];
						newobj[alias] = _number;					
					} else {
						alias = cols[j].alias ? cols[j].alias : cols[j].col;
						newobj[alias] = returnrecords[i][cols[j].col];
					}
				};
				returnobjs.records.push(newobj);
			};
		}
		else 
		{
			if(topcount&&(topcount>=0)) {
				returnobjs.records.length = topcount;
			}
		};
		
		if(returnobjs.records<1) {
			returnobjs.records = null;
		};
		return returnobjs.records;
	},
	
	DoSQL : function() {
		var Objs = [
						{
							id: 1,
							name: 'test'
						},
						{
							id: 2,
							name: 'test'
						},
						{
							id: 3,
							name: 'test'
						},
						{
							id: 4,
							name: 'test'
						}
					];
		var sql = 'select    name,id    from Objs where id>1';
		var tables = parseTables(sql);
		var objs = eval(tables);
		var cols = parseCols(sql);
		if (cols != "*") {
			var cols = splitCols(cols);
		};
		var conditions = parseConditions(sql);
		var conditions = splitConditions(conditions);
		
		var returnobjs = [];
		for(var i=0;i<objs.length;i++) {
			with(objs[i]) {
				var equalreturn = eval(conditions);
				if (equalreturn) {
					if (cols == "*") {
						returnobjs.push(objs[i]);
					} else {
						var newobj = {};
						for(var j=0;j<cols.length;j++) {
							newobj[cols[j]] = objs[j][cols[j]];
						};
						returnobjs.push(newobj);
					}
				}
			}
		}
		//alert(returnobjs);
	}
};


/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

	/*
	 * Insert SQL Language
	 * Can use basic insert language
	 */

YESBRAIN.JSQL.Memory.INSERT = {
	
		parseTable : function(sql){
		//var sql = "select * from test";
		var re = new RegExp(/\s*insert\s+into\s+(.+)\s*\(.+values/ig);
		var ree;
		var res;
		res = re.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseCols : function(sql) {
		var re = new RegExp(/\s*insert\s+into\s+.+\(\s*(.+)\s*\).*values/ig);
		//var sql = "select * from";
		var res;
		res = re.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseValues : function(sql) {
		var re = new RegExp(/.+values\s*\(\s*(.+)\s*\)/ig);
		//var sql = "select * from";
		var res;
		res = re.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	splitCols : function(cols) {
		var colsArr;
		var res;
		colsArr = cols.split(',');
		for(var i=0;i<colsArr.length;i++) {
			var re = new RegExp(/\s*(.+)\s*/ig);
			res = re.exec(colsArr[i]);
			if(res) {
				colsArr[i] = res[1];
			};
		};
		return colsArr;
	},
	
	splitValues : function(values) {
		var valueObjs = [];
		var valuesArr;
		var res;
		valuesArr = values.split(',');
		return valuesArr;
	},
	
	executeInsert : function(sql) {
		var table = this.parseTable(sql);
		table = eval(table);
		var cols = this.parseCols(sql);
		cols = this.splitCols(cols);
		var values = this.parseValues(sql);
		values = this.splitValues(values);
		if(cols.length!=values.length) {
			alert('cols or values format error!');
		};
		var row = {};
		for(var i=0;i<cols.length;i++) {
			row[cols[i]] = eval(values[i]);
		};
		table.push(row);
		return true;
	}
};


/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

	/*
	 * Update SQL Language
	 * Can use basic update language
	 */

YESBRAIN.JSQL.Memory.UPDATE = {
	parseTable : function(sql){
		//var sql = "select * from test";
		var re = new RegExp(/\s*update\s+(.+)\s+set/ig);
		var ree;
		var res;
		res = re.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseSettings : function(sql) {
		var re = new RegExp(/\s+where\s+/ig);
		var ree;
		var res;
		if(re.exec(sql)) {
			ree = new RegExp(/set\s+(.+)\s+where/ig);
		} else {
			ree = new RegExp(/set\s+(.+)$/ig);
		};
		res = ree.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		};
	},
	
	splitSettings : function(settings) {
		var settingsArr;
		var res;
		settingsArr = settings.split(',');
		for(var i=0;i<settingsArr.length;i++) {
			var re = new RegExp(/\s*(.+)\s*/ig);
			res = re.exec(settingsArr[i]);
			if(res) {
				settingsArr[i] = res[1];
			};
		};
		return settingsArr;
	},
	
	parseConditions : function(sql) {
		//var sql = "select * from test where a=a group by order by ";
		var res;
		var ree;
		var re = new RegExp(/\s+where\s+/ig);
		if(re.exec(sql)) {
			ree = new RegExp(/where(.+)$/ig);
			res = ree.exec(sql);
		} else {
			return "true";
		};
		if(res) {
			return res[1];
		}
		else {
			return null;
		};
	},
	
	
	equallike : function(Str, likeStr) {

		likeStr = likeStr.replace(/\%/ig,".+");
		likeStr = likeStr.replace(/\?/ig,".?");
		likeStr = likeStr.replace(/\*/ig,".?");
		var re2 = new RegExp(likeStr);
		re2.ignoreCase = true;
		re2.global = true;
		var ok = re2.exec(Str);
		return ok;
	},
	
	splitConditions : function(conditions) {
		var conditionsArr;
		var re = new RegExp(/(and|or)/ig);
		var re2 = new RegExp(/([^<=>])\=/ig);
		var re3 = new RegExp(/\s+(.+)\s+like\s+(.+)/ig);
		var res = '';
		conditionsArr = conditions.split(re);
		for(var i=0;i<conditionsArr.length;i++) {
			curCondition = conditionsArr[i];
			curCondition = curCondition.replace(re2,"$1==");
			curCondition = curCondition.replace(re3," this.equallike($1,$2)");
			conditionsArr[i] = curCondition;
		};
		for (var i = 0; i < conditionsArr.length; i++) {
			var tmpStr = conditionsArr[i];
			if (tmpStr.toLowerCase() == 'and') {
				tmpStr = '&&';
			}
			else if (tmpStr.toLowerCase() == 'or') {
				tmpStr = '||';
			};
			res = res + tmpStr;
		};
		return res;
	},
	
	executeUpdate : function(sql) {
		var table = this.parseTable(sql);
		table = eval(table);
		var settings = this.parseSettings(sql);
		var settingsArr = this.splitSettings(settings);
		
		var conditions = this.parseConditions(sql);
		conditions = this.splitConditions(conditions);
		
		var effectrowcount = 0;
		if(table.length<1) {return 0;};
		for(var i=0;i<table.length;i++) {
			with(table[i]) {
				var equalreturn = eval(conditions);
				if (equalreturn) {
					for(var j=0;j<settingsArr.length;j++) {
						var setting = settingsArr[j];
						eval(setting);
					};
					effectrowcount++;
				};
			};
		};
		return effectrowcount;
	}
};



/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

	/*
	 * Delete SQL Language
	 * Can use basic delete language
	 */

YESBRAIN.JSQL.Memory.DELETE = {

	parseTable : function(sql){
		var re = new RegExp(/\s+where\s+/ig);
		var ree;
		var res;
		if(re.exec(sql)) {
			ree = new RegExp(/from\s+(.+)\s+where/ig);
		} else {
			ree = new RegExp(/from\s+(.+)$/ig);
		};
		res = ree.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	parseConditions : function(sql) {
		//var sql = "select * from test where a=a group by order by ";
		var res;
		var ree;
		var re = new RegExp(/\s+where\s+/ig);
		if(re.exec(sql)) {
			ree = new RegExp(/where(.+)$/ig);
			res = ree.exec(sql);
		} else {
			return "true";
		};
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	
	equallike : function(Str, likeStr) {

		likeStr = likeStr.replace(/\%/ig,".+");
		likeStr = likeStr.replace(/\?/ig,".?");
		likeStr = likeStr.replace(/\*/ig,".?");
		var re2 = new RegExp(likeStr);
		re2.ignoreCase = true;
		re2.global = true;
		var ok = re2.exec(Str);
		return ok;
	},
	
	splitConditions : function(conditions) {
		var conditionsArr;
		var re = new RegExp(/(and|or)/ig);
		var re2 = new RegExp(/([^<=>])\=/ig);
		var re3 = new RegExp(/\s+(.+)\s+like\s+(.+)/ig);
		var res = '';
		conditionsArr = conditions.split(re);
		for(var i=0;i<conditionsArr.length;i++) {
			curCondition = conditionsArr[i];
			curCondition = curCondition.replace(re2,"$1==");
			curCondition = curCondition.replace(re3," this.equallike($1,$2)");
			conditionsArr[i] = curCondition;
		};
		for (var i = 0; i < conditionsArr.length; i++) {
			var tmpStr = conditionsArr[i];
			if (tmpStr.toLowerCase() == 'and') {
				tmpStr = '&&';
			}
			else if (tmpStr.toLowerCase() == 'or') {
				tmpStr = '||';
			};
			res = res + tmpStr;
		};
		return res;
	},
	
	executeDelete : function(sql) {
		var table = this.parseTable(sql);
		table = eval(table);
		
		var conditions = this.parseConditions(sql);
		conditions = this.splitConditions(conditions);
		
		var effectrowcount = 0;
		if(table.length<1) {return 0;};
		for(var i=0;i<table.length;i++) {
			with(table[i]) {
				var equalreturn = eval(conditions);
				if (equalreturn) {
					table.splice(i,1);
					i = i - 1;
					effectrowcount++;
				}
			}
		};
		return effectrowcount;
	}
};


/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

	/*
	 * Create Table SQL Language
	 * Can use basic create table language
	 */

YESBRAIN.JSQL.Memory.CREATETABLE = {
		
	parseTable : function(sql){
		var re = new RegExp(/\(.+\)/ig);
		var ree;
		var res;
		if(re.exec(sql)) {
			ree = new RegExp(/create\s+table\s+(.+)\s*\(/ig);
		} else {
			ree = new RegExp(/create\s+table\s+(.+)\s*$/ig);
		};
		res = ree.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	
	executeCreateTable : function(sql) {
		var table = this.parseTable(sql);
		if("undefined" == typeof window[table]) {
			window[table] = [];
			return true;
		} else {
			alert("table already existed");
			return false;
		};
	}
};



/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

	/*
	 * Drop Table SQL Language
	 * Can use basic drop table language
	 */

YESBRAIN.JSQL.Memory.DROPTABLE = {

	parseTable : function(sql){
		var re = new RegExp(/\(.+\)/ig);
		var ree;
		var res;
		if(re.exec(sql)) {
			ree = new RegExp(/drop\s+table\s+(.+)\s*\(/ig);
		} else {
			ree = new RegExp(/drop\s+table\s+(.+)\s*$/ig);
		};
		res = ree.exec(sql);
		if(res) {
			return res[1];
		}
		else {
			return null;
		}
	},
	
	
	executeDropTable : function(sql) {
		var table = this.parseTable(sql);
		if("undefined" == typeof window[table]) {
			alert("table not existed");
			return false;
		} else {
			delete window[table];
			return true;
		};
	}
};
